import apiService from '@/services/api'
// import {userInfo} from "node:os";
import {CozeAPI} from '@coze/api';
import { debounce } from 'lodash';
export default {
    name: 'TranslationV2',
    data() {
        return {
            // 通知系统
            notifications: [],
            notificationId: 0,
            filterText: '',
            debouncedFilterText: '',
            filterDebounce: null,
            visibleItems: [],
            maxVisibleItems: 100, // 最多显示100条

            // 分类数据
            detailData: {
                patch_data: {},
                translation: {}
            },
            //审核ID
            audit_id: 47,
            selectedCategory: NaN,

            // 搜索和排序
            searchQuery: '',
            sortField: 'file_id',
            sortOrder: 'asc',
            filter_translated: 'N/A',
            // 翻译者
            commit_user_id: -1,

            // 翻译条目数据
            items: [],
            //分页
            pagination: {
                has_next: false,
                has_prev: false,
                page: 1,
                pages: 0,
                per_page: 5,
                total: 0
            },
            showTranslationModal: false,
            currentTranslations: [],
            modalTitle: '',
            tooltipPosition: {
                top: 0,
                left: 0
            },
            allowCopy: false,
            currentItem: null,
            gossip_id: '',
            file_id: '',
        }
    },
    computed: {
        sourceText() {
            return this.detailData.patch_data?.content?.split('|||')?.join('\n')
        },
        sourceTranslated() {
            return this.detailData.translation?.content?.split('|||')?.join('\n')
        },
        filteredItems() {
            if (!this.filterText) {
                // 未过滤时也只显示前N条
                return this.items.slice(0, this.maxVisibleItems);
            }

            const filterLower = this.filterText.toLowerCase();
            const filtered = [];
            let count = 0;

            for (let i = 0; i < this.items.length && count < this.maxVisibleItems; i++) {
                const item = this.items[i];
                if (item.toString().toLowerCase().includes(filterLower)) {
                    filtered.push(item);
                    count++;
                }
            }

            return filtered;
        }
    },
    methods: {
        // userInfo,
        // 格式化时间显示
        formatDateTime(dateTime) {
            if (!dateTime) return '未知';
            try {
                const date = new Date(dateTime);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            } catch (error) {
                console.error('时间格式化失败:', error);
                return '未知';
            }
        },
        //uid: -1:清空；0：我翻译的；其它大于0：指定用户ID
        setUID(item) {
            this.detailData = {
                patch_data: {},
                translation: {}
            };
            this.selectedCategory = item;
            this.file_id = item
            this.fetchFetchDetail();
        },
        showTranslationList(translations, event, item) {
            console.log(item);
            this.currentItem = item;
            if (translations && translations.length > 0) {
                this.currentTranslations = translations;
                this.modalTitle = `翻译列表 (${translations.length} 个翻译)`;
                this.showTranslationModal = true;

                // 计算弹窗位置
                const rect = event.target.getBoundingClientRect();
                this.tooltipPosition = {
                    top: rect.bottom + window.scrollY + 5,
                    left: rect.left + window.scrollX
                };
            }
        },
        closeTranslationModal() {
            this.showTranslationModal = false;
            this.currentTranslations = [];
        },
        requireRole(level) {
            const currentUser = this.getCurrentUserInfo();
            if (!currentUser || !currentUser.user_id) {
                console.warn('未找到当前登录用户信息');
                return null;
            }
            return currentUser.role && currentUser.role > level
        },
        // 获取当前登录用户信息
        getCachedFileIds() {
            const file_ids = localStorage.getItem('file_ids');
            if (file_ids) {
                try {
                    return JSON.parse(file_ids);
                } catch (e) {
                    console.error('解析file_ids缓存失败:', e);
                    return null;
                }
            }
            return null;
        },
        // 获取当前登录用户信息
        getCurrentUserInfo() {
            const loginInfo = localStorage.getItem('loginInfo');
            if (loginInfo) {
                try {
                    return JSON.parse(loginInfo);
                } catch (e) {
                    console.error('解析登录信息失败:', e);
                    return null;
                }
            }
            return null;
        },
        getTranslationText(translations) {
            // 根据translations数组计算textarea的内容
            if (!translations || translations.length === 0) return '';

            let findUID = 0;
            if (this.allowEdit()) {//编辑模式
                // 获取当前登录用户信息
                const currentUser = this.getCurrentUserInfo();
                if (!currentUser || !currentUser.user_id) {
                    console.warn('未找到当前登录用户信息');
                    return null;
                }
                findUID = currentUser.user_id;
            } else {
                findUID = this.commit_user_id;
            }

            // 在items中查找commit_user等于当前user_id的第一条记录
            const firstTranslation = translations.find(item => {
                return item.commit_user && item.commit_user === findUID;
            });
            // 示例：返回第一个翻译或合并所有翻译
            return {chinese: firstTranslation?.content || '', remark: firstTranslation?.remark || ''};
        },
        allowEdit() {
            return this.selectedCategory <= 2;
        },
        copyTranslation(translation) {
            console.log(translation);
            if (translation.content) {
                if (this.currentItem != null) {
                    this.items.forEach(item => {
                        if (item.file_id == this.currentItem.file_id && item.gossip_id == this.currentItem.gossip_id) {
                            item.chinese = translation.content.substring(1, translation.content.length - 1);
                        }
                    });
                }

                this.showTranslationModal = false;
            }
        },
        checkValueNoChange(item) {
            if (item.chinese == undefined) {
                item.chinese = '';
            }
            if (item.translate_prev == undefined) {
                item.translate_prev = '';
            }
            return item.chinese === item.translate_prev;
        },
        // 从服务器获取翻译数据
        async fetchTranslations() {
            let cachedFileIds = this.getCachedFileIds()
            if (cachedFileIds) {
                this.items = cachedFileIds;
                console.log('使用本地缓存file_ids:');
                return
            }
            try {
                // 模拟API调用，实际项目中应替换为真实的API端点
                const response = await apiService.file_ids();
                if (response.success) {
                    this.items = response.data.data;
                    localStorage.setItem('file_ids', JSON.stringify(this.items));
                }
            } catch (error) {
                console.error('获取翻译数据失败:', error);
                this.error = '获取数据失败，请稍后重试';
                this.addNotification('error', '获取数据失败', '无法从服务器获取翻译数据');
            }
        },
        // 从服务器获取翻译数据详情
        async fetchFetchDetail() {
            const params = {
                file_id: this.file_id
            };
            try {
                // 模拟API调用，实际项目中应替换为真实的API端点
                const response = await apiService.detail(params);
                if (response.success) {
                    this.detailData = response.data.data;
                }
            } catch (error) {
                console.error('获取翻译数据失败:', error);
                this.error = '获取数据失败，请稍后重试';
                this.addNotification('error', '获取数据失败', '无法从服务器获取翻译数据');
            }
        },

        async fetchUserHistory() {
            let pageNum = 20;
            const params = {
                page: this.pagination.page,
                per_page: pageNum,
                search: this.searchQuery,
                sort_field: this.sortField,
                sort_order: this.sortOrder,
                is_translated: this.filter_translated,
                commit_users: this.commit_user_id
            };
            try {
                // 模拟API调用，实际项目中应替换为真实的API端点
                const response = await apiService.user_trans_history(params);
                if (response.success) {
                    this.items = response.data.data;
                    // 初始化每个 item 的 chinese 字段
                    this.items.forEach(item => {
                        item.chinese = item.content.substring(1, item.content.length - 1);//显示时去掉首尾中括号
                        item.content = item.English.substring(1, item.English.length - 1);//显示时去掉首尾中括号
                        item.updated_at = item.updated_at.substring(0, 19).replace('T', ' ');//显示时去掉毫秒
                        item.last_audit_at = '';
                        item.audited = false;
                        item.audited_content = '';
                        if (item.commit_user == this.audit_id) {
                            item.audited = true;
                            item.audited_content = item.chinese;
                        } else if (item.history && this.getCurrentUserInfo().user_id == this.audit_id && item.commit_user != this.audit_id) {
                            item.history.forEach(trans => {
                                console.log(trans.commit_user, this.audit_id);
                                if (trans.commit_user == this.audit_id) {
                                    console.log(trans.updated_at, item.updated_at);
                                    item.last_audit_at = trans.updated_at.substring(0, 19).replace('T', ' ');//显示时去掉毫秒
                                    if (item.last_audit_at >= item.updated_at) {
                                        item.audited = true;
                                        item.audited_content = trans.content.substring(1, trans.content.length - 1);//显示时去掉首尾中括号
                                    }
                                    return;
                                }
                            });
                        }
                    });
                    if (response.data.pagination) {
                        this.pagination = response.data.pagination;
                    } else {
                        console.warn('Pagination data is missing in response');
                    }
                }
            } catch (error) {
                console.error('获取翻译数据失败:', error);
                this.error = '获取数据失败，请稍后重试';
                this.addNotification('error', '获取数据失败', '无法从服务器获取翻译数据');
            }
        },
        // 保存翻译到服务器
        async saveTranslation(item) {
            try {
                const params = {
                    file_id: item.file_id,
                    gossip_id: item.gossip_id,
                    content: '[' + item.chinese + ']',//提交时检查并补回中括号
                    remark: item.remark
                }
                // 模拟API调用，实际项目中应替换为真实的API端点
                const response = await apiService.translation(params);
                if (response.success) {
                    item.translate_prev = item.chinese;//用于保存按钮的禁用启用
                    this.addNotification('success', '保存成功');
                }
            } catch (error) {
                console.error('保存翻译失败:', error);
                this.addNotification('error', '保存失败', `无法保存: ${params}`);
            }
        },

        //搜索关键词
        doSearch() {
            this.pagination.page = 1;
            this.fetchTranslations();
        },
        // 清空搜索
        clearSearch() {
            this.searchQuery = '';
            this.file_id = '';
            this.gossip_id = '';
            this.pagination.page = 1;
            this.fetchTranslations();
        },

        // 处理排序
        handleSort() {
            // 重置到第一页
            this.currentPage = 1;
        },

        // 切换排序顺序
        toggleSortOrder() {
            this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
            this.currentPage = 1;
        },

        // 按字段排序
        sortBy(field) {
            if (this.sortField === field) {
                // 如果点击的是当前排序字段，则切换排序顺序
                this.toggleSortOrder();
            } else {
                // 如果点击的是其他字段，则按该字段升序排序
                this.sortField = field;
                this.sortOrder = 'asc';
                this.currentPage = 1;
            }
            this.fetchTranslations();
        },

        // 上一页
        prevPage() {
            this.pagination.page--
            this.fetchTranslations();
        },

        // 下一页
        nextPage() {
            this.pagination.page++
            this.fetchTranslations();
        },


        // 添加通知
        addNotification(type, title, message) {
            const id = this.notificationId++;
            const notification = {
                id,
                type,
                title,
                message,
                progress: 0
            };

            this.notifications.push(notification);

            // 开始进度条动画
            const interval = setInterval(() => {
                if (notification.progress < 100) {
                    notification.progress += 2;
                } else {
                    clearInterval(interval);
                    // 进度完成后移除通知
                    this.removeNotification(id);
                }
            }, 30);

            // 5秒后自动移除通知
            setTimeout(() => {
                this.removeNotification(id);
            }, 5000);
        },

        // 移除通知
        removeNotification(id) {
            const index = this.notifications.findIndex(n => n.id === id);
            if (index !== -1) {
                this.notifications.splice(index, 1);
            }
        },
        adjustTextareaHeight(event) {
            const textarea = event.target;
            textarea.style.height = 'auto';
            textarea.style.height = textarea.scrollHeight + 'px';
        },
        async ask_ai(item) {
            if (item.translation == '' || item.translation == undefined) {
                const apiClient = new CozeAPI({
                    token: '',
                    baseURL: 'https://api.coze.cn',
                    allowPersonalAccessTokenInBrowser: true
                });
                const res = await apiClient.workflows.runs.create({
                    workflow_id: '',
                    parameters: {
                        "input": item.content
                    },
                });
                console.log(res.data);
                let result = JSON.parse(res.data.replaceAll("\\n", '\\\\n'));
                item.chinese = result.output;

                // let sample = "{\"output\":\"近战猎鹰攻击：命中时：你还会以正向治疗的方式回复你总生命值的15%。\\n\\n治疗增幅对该治疗效果有效，但法术强度无效。 \"}";
                // let result = JSON.parse(sample.replaceAll("\\n", '\\\\n'));
                // item.chinese = result.output;
            }
        }
    },

    watch: {
        selectedCategory() {
            // 分类改变时重置分页
            this.pagination.page = 1;
        },
        filterText: {
            handler(newVal) {
                if (this.filterDebounce) {
                    this.filterDebounce();
                }
            }
        }
    },
    mounted() {
        // ... 其他代码
        this.filterDebounce = debounce(() => {
            this.debouncedFilterText = this.filterText;
        }, 300);
        const currentUser = this.getCurrentUserInfo();
        if (!currentUser || !currentUser.user_id) {
            console.warn('未找到当前登录用户信息');
            return null;
        }
        // 组件挂载时获取数据
        this.fetchTranslations();
    }
}